package cn.fl.riskctrl.corp.service.impl;

import java.util.*;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.lionbridgecapital.loan.model.utils.DateUtils;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.riskctrl.corp.service.IRcWlTpMgtService;
import cn.fl.riskctrl.corp.vo.RcWlTpMgtVO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.Pager;
import rc.corpbaseinfo.base.dto.PageResponseDTO;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpAddApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpModifyApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.api.IRcCorpQueryApiService;
import rc.corpbaseinfo.facade.corpbaseinfo.condition.RcWlTpMgtQC;
import rc.corpbaseinfo.facade.corpbaseinfo.dto.RcWlTpMgtDTO;


/**
 * @Description: RC_WL_TP_MGT（物流小秘税开管理） 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class RcWlTpMgtServiceImpl implements IRcWlTpMgtService {

	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	@Autowired
	private IRcCorpQueryApiService rcCorpQueryApiService;
	@Autowired
	private IRcCorpAddApiService rcCorpAddApiService;
	@Autowired
	private IRcCorpModifyApiService rcCorpModifyApiService;
	@Autowired
	private IRcCorpApiService rcCorpApiService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
	/**
	 * SysUlFilesRec 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	@Override
	public RcWlTpMgtVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
        ResponseData<RcWlTpMgtDTO> responseData = rcCorpQueryApiService.selectRcWlTpMgtById(id);
        List<String> codeGrpCdList = new ArrayList<>();
        String corpCertTypCdDic = "RCT0044";
        codeGrpCdList.add(corpCertTypCdDic);
        Map<String, String> corpCertTypCdMap = new HashMap<>();
        Map<String, Map<String, String>> dicMap = null;
        String sysCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD);
        String orgCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD);
        dicMap = this.sysDictionaryApiService.searchMultiGroupToMap(sysCd, orgCd, codeGrpCdList);
        if(dicMap.containsKey(corpCertTypCdDic)){
            corpCertTypCdMap = dicMap.get(corpCertTypCdDic);
            if(CollectionUtils.isMapEmpty(corpCertTypCdMap)){
                corpCertTypCdMap = new HashMap<>();
            }
        }
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            RcWlTpMgtDTO dto = responseData.getData();
            RcWlTpMgtVO vo = new RcWlTpMgtVO();
            BeanUtils.copyProperties(dto,vo);
            vo.setCorpCertTypCdNm(corpCertTypCdMap.get(vo.getCorpCertTypCd()));
            return vo;
        }
		return null;
	}

	@Override
	public Long add(RcWlTpMgtVO entity) throws BaseException{
		if(null == entity){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		}
        RcWlTpMgtDTO dto = new RcWlTpMgtDTO();
        BeanUtils.copyProperties(entity,dto);
        //新增赋默认值
        Date date = new Date();
        dto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setCrtTm(date);
        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setMdfTm(date);
        ResponseData<Long> responseData = rcCorpAddApiService.addRcWlTpMgt(dto);
        if(Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)){
            return responseData.getData();
        }else{
            throw new BaseException(responseData.getMessage());
        }
	}

	@Override
	public boolean modify(RcWlTpMgtVO entity) throws BaseException{
		if (null == entity) {
			throw new BaseException("修改对象不能为空!");
		}

        if (entity.getIsValid() == 0) {
            throw new BaseException("信息已失效,不可修改!");
        }
        try {
            ResponseData response = rcCorpApiService.creditAuditAddRecordCallback(entity.getRcCstCorpBscInfoId());
            if (!Objects.equals(response.getCode(),ResponseData.SUCCESS_CODE)) {
                throw new BaseException(response.getMessage());
            }
        } catch (BaseException e) {
            throw new BaseException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException("信审补录回调异常");
        }
        RcWlTpMgtDTO dto = new RcWlTpMgtDTO();
        BeanUtils.copyProperties(entity,dto);
        //新增赋默认值
        Date date = new Date();
        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setMdfTm(date);
        ResponseData responseData = rcCorpModifyApiService.modifyRcWlTpMgt(dto);
        if (Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)) {
            try {
                rcCorpApiService.creditAuditExtRouteApi(entity.getRcCstCorpBscInfoId());
            } catch (Exception e) {
                BaseLogUtils.newLogger(e.getMessage()).error(LogExceptionEnum.COMMON_CODE_0001);
            }
            return true;
        } else {
            throw new BaseException(responseData.getMessage());
        }
	}

	@Override
	public Pager searchListPage(int pageSize, int pageNum, RcWlTpMgtQC qc) throws BaseException{
		ResponseData<PageResponseDTO<RcWlTpMgtDTO>> responseData = this.rcCorpQueryApiService.searchRcWlTpMgtListPage(pageSize, pageNum, qc);

        List<String> codeGrpCdList = new ArrayList<>();
        String corpCertTypCdDic = "RCT0044";
        codeGrpCdList.add(corpCertTypCdDic);
        Map<String, String> corpCertTypCdMap = new HashMap<>();
        Map<String, Map<String, String>> dicMap;
        String sysCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD);
        String orgCd = PropertiesCacheUtils.getProperty(SystemConstant.FL_ORG_CD);
        dicMap = this.sysDictionaryApiService.searchMultiGroupToMap(sysCd, orgCd, codeGrpCdList);
        if(dicMap.containsKey(corpCertTypCdDic)){
            corpCertTypCdMap = dicMap.get(corpCertTypCdDic);
            if(CollectionUtils.isMapEmpty(corpCertTypCdMap)){
                corpCertTypCdMap = new HashMap<>();
            }
        }
        Pager pager = new Pager();
        if (Objects.equals(responseData.getCode(),ResponseData.SUCCESS_CODE)) {
            PageResponseDTO pageDto = responseData.getData();
            if (null != pageDto && CollectionUtils.isNotEmpty(pageDto.getList())) {
                List<RcWlTpMgtVO> list = new ArrayList<>();
                for(Object dto : pageDto.getList()){
                    RcWlTpMgtVO vo = new RcWlTpMgtVO();
                    BeanUtils.copyProperties(dto,vo);
                    vo.setCorpCertTypCdNm(corpCertTypCdMap.get(vo.getCorpCertTypCd()));
                    if (FlowConstant.FLOW_CHECK_STATE_IN.equalsIgnoreCase(vo.getAudStsCd())) {
                        StringBuilder useTime = new StringBuilder();
                        int seconds = DateUtils.getSecondBetweenStartDateAndEndDateSecond(vo.getCrtTm(), new Date());
                        if (seconds > 0) {
                            int startHours = seconds/3600;
                            int startMinutes = (seconds%3600)/60;
                            int startSeconds = (seconds%3600)%60;
                            useTime.append(startHours).append("小时").append(startMinutes).append("分钟").append(startSeconds).append("秒");
                        }else{
                            useTime.append(0);
                        }
                        vo.setUseTime(useTime.toString());
                    }
                    if (FlowConstant.FLOW_CHECK_STATE_PASS.equalsIgnoreCase(vo.getAudStsCd())) {
                        StringBuilder passUseTime = new StringBuilder();
                        if (vo.getOperationCompletionTm() != null) {
                            int passSeconds = DateUtils.getSecondBetweenStartDateAndEndDateSecond(vo.getCrtTm(), vo.getOperationCompletionTm());
                            if (passSeconds > 0) {
                                int startHours = passSeconds/3600;
                                int startSeconds = (passSeconds%3600)%60;
                                int startMinutes = (passSeconds%3600)/60;
                                passUseTime.append(startHours).append("小时").append(startMinutes).append("分钟").append(startSeconds).append("秒");
                            }else{
                                passUseTime.append(0);
                            }
                        }
                        vo.setUseTime(passUseTime.toString());
                    }
                    list.add(vo);
                }
                pager.setTotalCount(pageDto.getTotalCount());
                pager.setResultList(list);
            }
        }
		return pager;
	}

	@Override
	public Long addFileRec(SysUlFilesRecQueryCondition fileQc, SysUlFilesRecVO fileRec) {
		this.sysUlFilesRecService.removeByCondition(fileQc);
		return this.sysUlFilesRecService.add(fileRec);
	}

    @Override
    public DataResultVO authThreeData(String rcCstCorpBscInfoId, String rcWlTpMgtId) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取三方数据成功!");
        try {
            ResponseData<RcWlTpMgtDTO> response = rcCorpApiService.authThreeData(Long.valueOf(rcCstCorpBscInfoId), Long.valueOf(rcWlTpMgtId));
            if (!Objects.equals(response.getCode(),ResponseData.SUCCESS_CODE)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_YES);
                try {
                    rcCorpApiService.creditAuditExtRouteApi(Long.valueOf(rcCstCorpBscInfoId));
                } catch (Exception e) {
                    BaseLogUtils.newLogger(e.getMessage()).error(LogExceptionEnum.COMMON_CODE_0001);
                }
            }
            result.setInfo(response.getMessage());
            RcWlTpMgtDTO rcWlTpMgtDTO = response.getData();
            result.setData(rcWlTpMgtDTO);
        } catch (BaseException e) {
            throw new BaseException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException("获取三方数据异常");
        }
        return result;
    }
}
